package com.atguigu.juc_day01;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther zzyy
 * @create 2022-06-14 22:37
 */
public class SyncLockDemo
{
    private Lock lock = new ReentrantLock();

    public synchronized void m1()
    {
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println(Thread.currentThread().getName()+"\t"+"---come in");
    }

    public void m2()
    {
        if (lock.tryLock()) {
            try
            {
                System.out.println(Thread.currentThread().getName()+"\t"+"---come in");
                TimeUnit.SECONDS.sleep(5);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }else{
            System.out.println(Thread.currentThread().getName()+"\t"+"没有抢到锁，放弃");
        }
    }

    public void m3()
    {
        try
        {
            if (lock.tryLock(3,TimeUnit.SECONDS)) {
                try
                {
                    System.out.println(Thread.currentThread().getName()+"\t"+"---come in");
                    TimeUnit.SECONDS.sleep(1);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }else{
                System.out.println(Thread.currentThread().getName()+"\t"+"3秒钟内没有抢到锁，放弃");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
        SyncLockDemo syncLockDemo = new SyncLockDemo();

        new Thread(() -> {
            syncLockDemo.m3();
        },"t1").start();

        new Thread(() -> {
            syncLockDemo.m3();
        },"t2").start();
    }
}
 
 
